package com.sxt.server.init;

import java.nio.charset.Charset;
import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.sxt.server.common.JT808Const;
import com.sxt.server.encode.JT808Decoder;
import com.sxt.server.handle.Jt808MsgHandle;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.util.concurrent.DefaultEventExecutorGroup;
import io.netty.util.concurrent.EventExecutorGroup;
import io.netty.channel.socket.SocketChannel;

/**
 * 
 * @author Administrator
 *
 */

@Component
public class JT808ChannelInitializer extends ChannelInitializer<SocketChannel> {

	@Value("${netty.read-timeout}")
	private int readTimeOut;

	//业务连接池
	static final EventExecutorGroup businessGroup = new DefaultEventExecutorGroup(20);
	
	@Override
	protected void initChannel(SocketChannel socketChannel) throws Exception {
		// TODO Auto-generated method stub
		ChannelPipeline pipeline = socketChannel.pipeline();
		// 15分钟没有收到消息 将IdleStateHandler 添加到 ChannelPipeline 中
		pipeline.addLast("idleStateHandler", new IdleStateHandler(readTimeOut, 0, 0, TimeUnit.MINUTES));
		// jt808协议 包头最大长度16+ 包体最大长度1023+分隔符2+转义字符最大姑且算60 = 1100
		pipeline.addLast(
				new DelimiterBasedFrameDecoder(1024, Unpooled.copiedBuffer(new byte[] { JT808Const.PKG_DELIMITER }),
						Unpooled.copiedBuffer(new byte[] { JT808Const.PKG_DELIMITER, JT808Const.PKG_DELIMITER })));
		pipeline.addLast(new JT808Decoder());// 解码器
		pipeline.addLast(new StringEncoder(Charset.forName("GBK")));//  消息转成String编码器
		pipeline.addLast(businessGroup, new Jt808MsgHandle());
	}

}
